import axios from 'axios'
// import store from '@/store'
import { getToken } from './auth'
import { Message } from 'element-ui'
import router from '@/router'
import store from '@/store'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 10000
})

service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use((response) => {
  if (response.data instanceof Blob) return response.data
  const { data, msg, code } = response.data
  if (code === 10000) {
    return data
  } else {
    Message.error(msg)
    return Promise.reject(new Error(msg))
  }
}, (error) => {
  if (error.response) {
    if (error.response.status === 401) {
      Message.error('尊敬的用户，当前登录状态已过期！')
      store.commit('user/REMOVE_TOKEN')
      router.replace('/login')
    } else {
      Message({
        type: 'error',
        message: error.response.data.msg,
        duration: 5000
      })
    }
  }
  // console.log(error.response)

  return Promise.reject(error)
})

export default service
